import { OdooJSRPC as JSRPC } from '../odoojs-rpc1/index.js'

import { Action } from './action.js'
import { RelationNode } from './relationnode.js'

import { eval_helper } from './eval_helper.js'

export class OdooJSRPC extends JSRPC {
  constructor(payload) {
    // const { debug, run_by_server } = payload
    // const { Request, baseURL, timeout, messageError } = payload
    super(payload)

    // 当前用户的权限组
    this._groups = []

    this._lang = null
  }

  get lang() {
    return this._lang || 'en_US'
  }

  set lang(lang) {
    this._lang = lang
  }

  async after_session() {
    if (!this._lang) {
      this._lang = this.web.session.lang
    }
    super.after_session()
  }

  _action_load(action, { actions }) {
    const [mod, action_name] = action.split('.')
    const info = actions[mod][action_name]

    if (!info) {
      console.log(`${action} no defined`)
      throw `${action} no defined`
    }

    return info
  }

  action(action_name, kws = {}) {
    const { models = {}, actions, metadata, ...action_info } = kws
    const config = this._action_load(action_name, { actions })

    const that = this

    function ctx_get() {
      const { context: ctx0 = {} } = config
      const ctx1 = context_get(ctx0, { env: that.env })
      const { context: ctx2 = {} } = action_info
      const ctx3 = { ...ctx1, ...ctx2 }
      return ctx3
    }

    const context = ctx_get()

    const config2 = { ...config, ...action_info, context }

    return new Action(config2, { rpc: this, models, metadata })
  }

  relation_node(node, kws = {}) {
    //   管理  o2m 节点
    const { models = {} } = kws
    return new RelationNode(node, { rpc: this, models })
  }
}

const my_storage = {
  rpc: null
}

export function get_odoojs_rpc(payload) {
  // const { Request, baseURL, timeout, run_by_server, messageError } = payload

  if (my_storage.rpc) {
    return my_storage.rpc
  } else {
    const rpc = new OdooJSRPC(payload)
    my_storage.rpc = rpc
    return rpc
  }
}

function context_get(ctx, kws = {}) {
  // const { context, record } = kws

  // console.log(' context_get ', ctx, kws)

  const ctx2 = Object.keys(ctx).reduce((acc, cur) => {
    const todo = ctx[cur]
    if (['string', 'number', 'boolean'].includes(typeof todo)) {
      acc[cur] = todo
    } else if (Array.isArray(todo)) {
      acc[cur] = todo
    } else if (typeof todo === 'object') {
      acc[cur] = eval_helper.eval_object(todo, kws)
    } else {
      console.log('context_get. doing', ctx, cur, todo)
      throw 'error, context_get' + JSON.stringify(ctx)
    }

    return acc
  }, {})

  // console.log(' context_get 2', ctx2)

  return ctx2
}
